import {
  type ComputedRef,
  getCurrentInstance,
  type Ref,
  shallowReactive,
  computed,
  unref,
  watch,
} from 'vue';
import type { AdvanceState, ColEx, FormProps, FormSchema, Recordable } from '../types/form';

import type { EmitType } from '../common/gloab';
import { isBoolean, isFunction, isNumber, isObject } from 'lodash-es';
import { createBreakpointListen } from './useBreakpoint';
import { useDebounceFn } from '@vueuse/core';

const BASIC_COL_LEN = 24;

interface UseAdvancedContext {
  advanceState: AdvanceState;
  emit: EmitType;
  getProps: ComputedRef<FormProps>;
  getSchema: ComputedRef<FormSchema[]>;
  formModel: Recordable;
  defaultValueRef: Ref<Recordable>;
}

export default function ({
  advanceState,
  emit,
  getProps,
  getSchema,
  formModel,
  defaultValueRef,
}: UseAdvancedContext) {
  const vm = getCurrentInstance();
  // 空白行格
  const getEmptySpan = computed((): number => {
    if (!advanceState.isAdvanced) {
      return 0;
    }
    // For some special cases, you need to manually specify additional blank lines
    const emptySpan = unref(getProps).emptySpan || 0;

    if (isNumber(emptySpan)) {
      return emptySpan;
    }
    if (isObject(emptySpan)) {
      const { span = 0 } = emptySpan as ColEx;
      return span || 0;
    }
    return 0;
  });
  const { realWidthRef, screenEnum } = createBreakpointListen();
  // console.log("realWidthRef", realWidthRef)
  const debounceUpdateAdvanced = useDebounceFn(updateAdvanced, 30);

  watch(
    [() => unref(getSchema), () => advanceState.isAdvanced, () => unref(realWidthRef)],
    () => {
      debounceUpdateAdvanced();
    },
    { immediate: true },
  );
  // 计算col
  function getAdvanced(itemCol: Partial<ColEx>, itemColSum = 0, _isLastAction = false) {
    const width = unref(realWidthRef);
    const sxWidth = parseInt(itemCol.xs as string) || (itemCol.span as number) || BASIC_COL_LEN;
    const smWidth = parseInt(itemCol.sm as string) || sxWidth;
    const mdWidth = parseInt(itemCol.md as string) || smWidth;
    const lgWidth = parseInt(itemCol.lg as string) || mdWidth;
    const xlWidth = parseInt(itemCol.xl as string) || lgWidth;
    if (width >= screenEnum.XL) {
      // console.log("xl", xlWidth)
      itemColSum += xlWidth;
    } else if (width >= screenEnum.LG) {
      // console.log("lg", lgWidth)
      itemColSum += lgWidth;
    } else if (width >= screenEnum.MD) {
      // console.log("md", mdWidth)
      itemColSum += mdWidth;
    } else if (width >= screenEnum.SM) {
      // console.log("sm", smWidth)
      itemColSum += smWidth;
    } else if (width >= screenEnum.XS) {
      // console.log("XS", sxWidth)
      itemColSum += sxWidth;
    } else {
      itemColSum += sxWidth;
    }

    // if (isLastAction) {
    //   advanceState.hideAdvanceBtn = false
    //   if (itemColSum <= BASIC_COL_LEN * 2) {
    //     // When less than or equal to 2 lines, the collapse and expand buttons are not displayed
    //     advanceState.hideAdvanceBtn = true
    //     advanceState.isAdvanced = true
    //   } else if (itemColSum > BASIC_COL_LEN * 2 && itemColSum <= BASIC_COL_LEN * (unref(getProps).autoAdvancedLine || 3)) {
    //     advanceState.hideAdvanceBtn = false

    //     // More than 3 lines collapsed by default
    //   } else if (!advanceState.isLoad) {
    //     advanceState.isLoad = true
    //     advanceState.isAdvanced = !advanceState.isAdvanced
    //   }
    //   return { isAdvanced: advanceState.isAdvanced, itemColSum }
    // }

    if (itemColSum > BASIC_COL_LEN * (unref(getProps).alwaysShowLines || 100)) {
      return { isAdvanced: advanceState.isAdvanced, itemColSum };
    } else {
      return { isAdvanced: true, itemColSum };
    }
  }

  const fieldsIsAdvancedMap: any = shallowReactive({});

  function updateAdvanced() {
    let itemColSum = 0;
    let realItemColSum = 0;
    const { baseColProps = {} } = unref(getProps);

    for (const schema of unref(getSchema)) {
      const { show, colProps } = schema;
      let isShow = true;

      if (isBoolean(show)) {
        isShow = show;
      }

      if (isFunction(show)) {
        isShow = show({
          schema: schema,
          model: formModel,
          field: schema.field,
          values: {
            ...unref(defaultValueRef),
            ...formModel,
          },
        });
      }

      if (isShow && (colProps || baseColProps)) {
        const { itemColSum: sum, isAdvanced } = getAdvanced(
          { ...baseColProps, ...colProps },
          itemColSum,
        );
        // console.log("itemColSum", isAdvanced, sum)
        itemColSum = sum || 0;
        if (isAdvanced) {
          realItemColSum = itemColSum;
        }
        // 是否显示
        fieldsIsAdvancedMap[schema.field] = isAdvanced;
      }
    }

    // 确保页面发送更新
    vm?.proxy?.$forceUpdate();
    // console.log("realItemColSum", realItemColSum)
    advanceState.actionSpan = (realItemColSum + unref(getEmptySpan)) % BASIC_COL_LEN;
    getAdvanced({ span: BASIC_COL_LEN }, itemColSum, true);
    emit('advanced-change');
  }

  function handleToggleAdvanced() {
    advanceState.isAdvanced = !advanceState.isAdvanced;
  }

  return { handleToggleAdvanced, fieldsIsAdvancedMap };
}
